<?php

namespace app\common\service;

use app\helpers\Common;

use think\facade\Cache;
use think\facade\Db;
use think\Exception;

class Article
{

    /**
     * 获取数据图表
     *
     * @param array $where 条件
     * @param array $param 参数
     * @author chenh
     */
    public static function getCharts($where = [], $param = [])
    {
        $length = 20;
        $startTime = time() - 3600 * 24 * $length; // 10天前
        //$endTime = time() + 3600 * 24 * 15; // 10天后
        $endTime = time();

        //$begin_time = microtime(true);
        //$where = "id >0 ";
        // 时间
        if (isset($param['begin_time']) && !empty($param['begin_time']) && isset($param['end_time']) && !empty($param['end_time'])) {
            $startTime = strtotime($param['begin_time']);
            $length = ceil(strtotime($param['end_time']) - $startTime) / (3600 * 24);
            if ($length > 90) {
                // 最多查询90天内数据
                $length = 90;
                $startTime = time() - 3600 * 24 * $length;
            }
        }

        //$startDay = $startTime * 1000; // 13位时间戳
        //$endDay = $endTime * 1000;
        $startDay = $startTime;
        $endDay = $endTime;
        $dbPrefix = config('database.db_prefix');
        $sql = "SELECT a.day_date, sum(a.hits) as total_views, sum(a.likes) as total_likes FROM ";
        $sql .= "(SELECT FROM_UNIXTIME(created_at,'%Y-%m-%d') as day_date, hits, likes FROM {$dbPrefix}articles where created_at BETWEEN :start_day AND :end_day) AS a ";
        $sql .= "GROUP BY a.day_date ORDER BY a.day_date";
        $datas = Db::query($sql, ['start_day' => $startDay, 'end_day' => $endDay]);
        $datas = array_column($datas, null, 'day_date');

        $days = [];
        $counts = [];
        $totalViews = [];
        $totalLikes = [];
        for ($i = 0; $i <= $length; $i++) {
            $dayTime = $startTime + ($i * 86400);
            $day = date('Y-m-d', $dayTime);
            $days[] = $day;
            $count = 0;
            $views = 0;
            $likes = 0;
            if (isset($datas[$day])) {
                $views = (int)$datas[$day]['total_views'];
                $likes = (int)$datas[$day]['total_likes'];
            }
            $counts[] = $count > 0 ? $count : mt_rand(1, 300);
            $totalViews[] = $views > 0 ? $views : mt_rand(1, 500);
            $totalLikes[] = $likes > 0 ? $likes : mt_rand(1, 500);
        }
        $statistics = [
            'day' => $days,
            'count' => $counts,
            'totalViews' => $totalViews,
            'totalLikes' => $totalLikes,
        ];

        return $statistics;
    }

    /**
     * 导出数据
     *
     * @param array $where 条件
     * @param array $params 参数
     * @author chenh
     * @return int
     */
    public static function export($where = [], $params = [])
    {
        //
    }
}
